package com.ruoyi.crm.Listener;

import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.ruoyi.common.config.DDConstant;
import com.ruoyi.common.enums.flow.FlowTypeEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.dd.MessageUtil;
import com.ruoyi.common.utils.flow.FlowDTO;
import com.ruoyi.crm.domain.CrmOrder;
import com.ruoyi.crm.domain.CrmTask;
import com.ruoyi.crm.mapper.CrmOrderMapper;
import com.ruoyi.crm.mapper.CrmTaskMapper;
import com.ruoyi.crm.strategy.CrmOrderContext;
import com.ruoyi.crm.strategy.CrmOrderFlowStrategy;
import com.taobao.api.ApiException;
import com.warm.flow.core.entity.Instance;
import com.warm.flow.core.listener.Listener;
import com.warm.flow.core.listener.ListenerVariable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.Map;

/**
 * 费用申请启动监听器
 *
 * @author 陈彬彬
 * @date 2023-04-11
 */
@Component
@Slf4j
public class CrmFeeApplyListener implements Listener {

  @Value("${approver.userId}")
  private String userId;

  @Autowired
  private CrmOrderContext crmOrderContext;

  /**
   * 费用申请发送钉钉通知审批人
   *
   * @author 陈彬彬
   * @date 2023-04-11
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void notify(ListenerVariable variable) {
    log.error("开始监听器;{}", variable);
    OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
    msg.setMsgtype("markdown");
    msg.setMarkdown(new OapiMessageCorpconversationAsyncsendV2Request.Markdown());
    msg.getMarkdown().setTitle("费用申请审批提醒");
    Instance instance = variable.getInstance();
    String text = this.builder(instance);
    msg.getMarkdown().setText(text);
      //发送钉钉 工作通知
      try {
          MessageUtil.send(userId, msg);
      } catch (ApiException e) {
          throw new RuntimeException(e);
      }

    }

    private String builder(Instance instance){
      Long definitionId = instance.getDefinitionId();
      String businessId = instance.getBusinessId();
      String name = FlowTypeEnum.getNameByDefinitionId(definitionId.toString());
      CrmOrderFlowStrategy orderFlowService = crmOrderContext.getOrderFlowService(name);
      FlowDTO flowDTO = orderFlowService.conversionObjByLocal(businessId);

      StringBuilder text = new StringBuilder();
      text.append("## " + flowDTO.getSubmitUser() + "提交的费用申请，请审批！");
      text.append("  \n  ");
      Map<String, Object> businessValue = flowDTO.getBusinessValue();
      Iterator<Map.Entry<String, Object>> iterator = businessValue.entrySet().iterator();
      while (iterator.hasNext()) {
        Map.Entry<String, Object> entry = iterator.next();
        text.append(entry.getKey() + ": " + entry.getValue());
        text.append("  \n  ");
      }

      text.append("  \n  ");
      text.append("[立即查看](" + DDConstant.DD_FRONT_URL + DDConstant.FRONT_URL_HOST + "flow/todo)");
      return text.toString();
    }
}
